<template>
  <Category :btnNumber="btnNumber"></Category>
  <el-card style="margin-top: 20px">
    <div v-show="btnNumber == 1 ? false : true">
      <el-button
        @click="btnShow"
        type="primary"
        :icon="Plus"
        :disabled="useproductCategoryStore.c3Id ? false : true"
        >添加平台属性</el-button
      >
      <transition name="tableAttr">
        <el-table
          v-show="attributesList.length"
          :data="attributesList"
          style="margin-top: 20px"
          :border="true"
        >
          <el-table-column
            align="center"
            width="100"
            label="序号"
            type="index"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            align="center"
            min-width="10%"
            label="属性名称"
          ></el-table-column>
          <el-table-column align="center" min-width="50%" label="属性值">
            <template #="{ row }">
              <el-tag
                style="margin: 10px"
                v-for="item in row.attrValueList"
                :key="item.id"
                :type="item.id % 2 === 0 ? 'success' : 'warning'"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="10" label="操作">
            <template #="{ row }">
              <el-popconfirm
                @confirm="deleteAttrBtn(row.id)"
                :width="220"
                :title="`要删除${row.attrName}吗？`"
              >
                <template #reference>
                  <el-button
                    size="small"
                    :icon="Delete"
                    type="danger"
                  ></el-button>
                </template>
              </el-popconfirm>

              <el-button
                @click="updataAttr(row)"
                size="small"
                type="warning"
                :icon="Edit"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>

      <el-empty
        v-show="!attributesList.length"
        :image-size="600"
        image="https://www.xiaoweio.com/wp-content/uploads/2023/07/1690345210897.gif"
        description="数据暂为空"
      />
    </div>
    <div v-show="btnNumber == 1 ? true : false">
      <el-form size="large" :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="输入属性名称"
            v-model="attributesParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        :disabled="attributesParams.attrName ? false : true"
        type="primary"
        :icon="Plus"
        @click="addAttValue"
        >添加属性值</el-button
      >
      <el-button @click="btnNumber = 0">取消</el-button>
      <el-table
        border
        style="margin: 15px 0"
        :data="attributesParams.attrValueList"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          :width="100"
        ></el-table-column>
        <el-table-column label="属性值" :min-width="40" align="center">
          <template #="{ row, $index }">
            <el-input
              ref="inputRef"
              v-if="row.inputShow"
              @blur="inputBlur(row, $index)"
              placeholder="输入属性名"
              v-model="row.valueName"
            ></el-input>
            <div v-else @click="clickDiv(row)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column :min-width="40" label="操作">
          <template #="{ row, $index }">
            <el-button
              @click="attributesParams.attrValueList.splice($index, 1)"
              type="danger"
              :icon="CircleCloseFilled"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="addAttributeBtn"
        :disabled="
          attributesParams.attrName && attributesParams.attrValueList.length
            ? false
            : true
        "
        >保存</el-button
      >
      <el-button @click="btnNumber = 0">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import {
  delAttribute,
  reqAddOrUpdateAttr,
  reqGetProductBaseList,
} from "@/api/product/attributes";
import type {
  productAttribute,
  productAttributeData,
  productAttributeObject,
} from "@/api/product/type/type";
import productCategoryStore from "@/stores/category";
import { Plus, Delete, Edit, CircleCloseFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { nextTick, ref, watch } from "vue";
import cloneDeep from "lodash/cloneDeep";
//获取属性管理拿到select框信息
const useproductCategoryStore = productCategoryStore();
//监听三级分类id变化，并且存在值
watch(
  () => useproductCategoryStore.c3Id,
  () => {
    //三级Id变化要清空数据数组
    attributesList.value = [];
    //获取平台属性函数函数
    getAttributeList();
  }
);
//存储平台属性数组
const attributesList = ref<productAttributeData>([]);
//获取平台属性函数函数
const getAttributeList = async () => {
  const { c1Id, c2Id, c3Id } = useproductCategoryStore;
  const res: productAttributeData = await reqGetProductBaseList(
    c1Id,
    c2Id,
    c3Id
  );
  attributesList.value = res;
};
//添加平台属性的按钮
const btnNumber = ref(0);
const btnShow = () => {
  //添加前清空残余数据
  Object.assign(attributesParams.value, {
    id: "",
    categoryId: "", //三级分类Id
    categoryLevel: 3, //第几级分类,固定的
    attrName: "", // 新增属性的名字,
    attrValueList: [], //新增属性的数组值
  });
  btnNumber.value = 1;
};
//添加商品属性参数
const attributesParams = ref<productAttributeObject>({
  categoryId: "", //三级分类Id
  categoryLevel: 3, //第几级分类,固定的
  attrName: "", // 新增属性的名字,
  attrValueList: [], //新增属性的数组值
});
//添加属性值按钮
const addAttValue = () => {
  attributesParams.value.attrValueList.push({
    valueName: "",
    inputShow: true,
  });
  //输入属性值input聚焦
  nextTick(() => {
    inputRef.value.focus();
  });
  //取到categoryId三级分类id
  attributesParams.value.categoryId = useproductCategoryStore.c3Id;
};
//请求添加属性的接口函数
const addAttributeAPI = async () => {
  try {
    await reqAddOrUpdateAttr(attributesParams.value);

    ElMessage({
      message: attributesParams.value.id ? "修改成功" : "添加成功",
      type: "success",
    });
  } catch (error) {
    ElMessage({
      message: attributesParams.value.id ? "修改失败" : "添加失败",
      type: "error",
    });
  }
};
//添加属性页面保存提交的按钮
const addAttributeBtn = () => {
  addAttributeAPI();
  //重新获取数据
  getAttributeList();
  btnNumber.value = 0;
};
//输入属性值输入框实例
const inputRef = ref();
//监听输入商品属性值输入框失去焦点函数
const inputBlur = (row: productAttribute, index: number) => {
  //输入为空不可以
  if (row.valueName == "") {
    ElMessage({
      type: "error",
      message: "输入不能为空",
    });
    //index从0开始
    //删除这个不合法元素
    attributesParams.value.attrValueList.splice(index, 1);

    return;
  }
  //如果与上面输入成功的值相同也不可以
  const isRepeat = attributesParams.value.attrValueList.find(
    (item: productAttribute) => {
      if (item != row) {
        return item.valueName.trim() == row.valueName.trim();
      }
    }
  );
  if (isRepeat) {
    //删除这个不合法元素
    attributesParams.value.attrValueList.splice(index, 1);
    ElMessage({
      type: "error",
      message: "输入属性重复",
    });
  }

  row.inputShow = false;
};
//监听点击属性值div事件
const clickDiv = (row: productAttribute) => {
  row.inputShow = true;
  ////输入属性值input聚焦
  nextTick(() => {
    inputRef.value.focus();
  });
};
//更新属性数据
const updataAttr = (row: productAttributeObject) => {
  //先深度便利
  // 方法一：Object.assign(attributesParams.value, JSON.parse(JSON.stringify(row)));
  Object.assign(attributesParams.value, cloneDeep(row));
  btnNumber.value = 1;
};
//删除属性函数
const deleteAttrBtn = async (id: number | string) => {
  await delAttribute(id);
  //重新拉取数据
  getAttributeList();
  ElMessage({
    type: "success",
    message: "删除成功",
  });
};
</script>

<style scoped>
/* 进入开始的动画状态 */
.tableAttr-enter-from {
  transform: scale(0);
}
/* 进入到离开中间过程中的动画 */
.tableAttr-enter-active {
  transition: all 0.3s;
}
/* 进入结束的动画状态 */
.tableAttr-enter-to {
  transform: scale(1);
}
/* 离开的动画状态 */
.tableAttr-leave-from {
  transform: scale(1);
}
/* 离开中间过程的动画 */
.tableAttr-leave-active {
  transition: all 0.4s;
}
/* 离开结束的动画状态 */
.tableAttr-leave-to {
  transform: scale(0);
}
</style>
